package hlhj.fhp.tvlib.activitys

import android.os.Build
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.View
import com.google.gson.Gson
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.listener.LockClickListener
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.tenma.ventures.bean.utils.TMSharedPUtil
import hlhj.fhp.tvlib.Contents
import hlhj.fhp.tvlib.R
import hlhj.fhp.tvlib.adapter.LivePagerAdp
import hlhj.fhp.tvlib.customView.GoLoginDialog
import hlhj.fhp.tvlib.fragment.LiveCommentFgm
import hlhj.fhp.tvlib.fragment.LiveInfoFgm
import hlhj.fhp.tvlib.javabean.BaseBean
import hlhj.fhp.tvlib.javabean.DanMuBean
import hlhj.fhp.tvlib.javabean.LiveDetailBean
import hlhj.fhp.tvlib.video.DanmakuVDPlayer
import kotlinx.android.synthetic.main.activity_live_aty_tv.*
import java.util.ArrayList

class LiveAty : BaseAty(), DanmakuVDPlayer.OnEditClickListener {


    private lateinit var  orientationUtils: OrientationUtils
    private var isPlay=false
    private var url="rtmp://live.hkstv.hk.lxdns.com/live/hks"
    private lateinit var infoFgm:Fragment
    private lateinit var commentFgm:Fragment
    private val fgmList=ArrayList<Fragment>()
    private lateinit var pagerAdp:LivePagerAdp
    companion object {
        var isLay=false
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar!!.hide()
        setPlayer()
        initListener()
        setPager(intent.getIntExtra("id",0).toString())
        OkGo.get<String>(Contents.BaseUrl + Contents.LIVE_DETAIL)
                .params("live_id", intent.getIntExtra("id",0).toString())
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val str = response?.body()
                        val detailBean = Gson().fromJson(str, LiveDetailBean::class.java)
                        if (detailBean.code==1){
                            if (detailBean.data.vote_status==1){
                                gsyPlayer.btEdit.visibility=View.VISIBLE
                            }else if (detailBean.data.vote_status==2){
                                gsyPlayer.btEdit.visibility=View.GONE
                            }
                        }
                    }
                })
        btExit.setOnClickListener {
            finish()
//            supportActionBar?.hide()
        }
    }

    override fun getContentId(): Int {
        return R.layout.activity_live_aty_tv
    }
    private fun getDamu() {
        OkGo.get<String>(Contents.BaseUrl+Contents.GET_DANMU)
                .params("live_id",intent.getIntExtra("id",0).toString())
                .execute(object :StringCallback(){
                    override fun onSuccess(response: Response<String>?) {
                        val str = response?.body()
                        val bean = Gson().fromJson(str, DanMuBean::class.java)
                        if (bean?.code==1){
                            gsyPlayer.addDanmu(bean)
                        }
                    }
                })
    }

    private fun initListener() {
        tablayout.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                viewPager.currentItem=tab?.position!!
            }
        })
        viewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {

            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                tablayout.getTabAt(position)!!.select()
            }
        })
    }

    private fun setPager(id:String) {
        infoFgm=LiveInfoFgm.getInstence(id,1)
        commentFgm=LiveCommentFgm.getInstence(id)
        fgmList.add(infoFgm)
        fgmList.add(commentFgm)
        pagerAdp=LivePagerAdp(supportFragmentManager,fgmList)

        viewPager.adapter=pagerAdp
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        supportActionBar?.hide()
    }
    private fun setPlayer() {
        gsyPlayer.setUp(intent.getStringExtra("url"), true, intent.getStringExtra("tittle"))
        gsyPlayer.startButton.performClick()
        orientationUtils = OrientationUtils(this, gsyPlayer)
        orientationUtils.isEnable = false
        //初始化不打开外部的旋转
        gsyPlayer.setIsTouchWiget(true);
        //关闭自动旋转
        gsyPlayer.setRotateViewAuto(false);
        gsyPlayer.setLockLand(false);
        gsyPlayer.setShowFullAnimation(false);
        gsyPlayer.setNeedLockFull(true);
        gsyPlayer.setOnEditClickListener(this)
        gsyPlayer.setVideoAllCallBack(object : GSYSampleCallBack() {
            override fun onPrepared(url: String?, vararg objects: Any?) {
                super.onPrepared(url, *objects)
                orientationUtils.isEnable = true
                isPlay = true
                getDamu()
            }
            override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                super.onQuitFullscreen(url, *objects)
                if (orientationUtils != null) {
                    LiveAty.isLay=false
                    gsyPlayer.fullscreenButton.visibility=View.VISIBLE
                    orientationUtils.backToProtVideo()
                }
            }

            override fun onAutoComplete(url: String?, vararg objects: Any?) {
                super.onAutoComplete(url, *objects)
            }

            override fun onClickStartError(url: String?, vararg objects: Any?) {
                super.onClickStartError(url, *objects)
            }
        })
        gsyPlayer.setLockClickListener(object : LockClickListener {
            override fun onClick(view: View?, lock: Boolean) {
                if (orientationUtils != null) {
                    //配合下方的onConfigurationChanged
                    orientationUtils.isEnable = !lock
                }
            }
        })
        gsyPlayer.getTitleTextView().setVisibility(View.GONE);
        gsyPlayer.getBackButton().setVisibility(View.GONE);

        gsyPlayer.fullscreenButton.setOnClickListener {
            orientationUtils.resolveByClick()
            LiveAty.isLay=true
            gsyPlayer.fullscreenButton.visibility=View.GONE
            val player = gsyPlayer.startWindowFullscreen(this, false, true) as DanmakuVDPlayer
            player.setOnEditClickListener(this)

        }
    }

    override fun onPause() {
        gsyPlayer.onVideoPause()
        super.onPause()
    }

    override fun onDestroy() {
        Log.e("fhp","走一次销毁")
        super.onDestroy()
        gsyPlayer.release()
    }

    override fun onResume() {
        gsyPlayer.onVideoResume()
        super.onResume()
    }
    public fun sendDM(str:String){
        if (TMSharedPUtil.getTMToken(this).equals("")||TMSharedPUtil.getTMToken(this)==null){
            GoLoginDialog(this).show()
        }else{
            gsyPlayer.addDanmaku(str,true)

            OkGo.get<String>(Contents.BaseUrl+Contents.SEND_DANMU)
                    .params("token",TMSharedPUtil.getTMToken(this@LiveAty))
                    .params("live_id",intent.getIntExtra("id",0).toString())
                    .params("vote_content",str)
                    .execute(object :StringCallback(){
                        override fun onSuccess(response: Response<String>?) {
                            val str = response?.body()
                            val bean = Gson().fromJson(str, BaseBean::class.java)
                            if (bean?.code==1){

                            }
                        }
                    })
        }
    }
    override fun sendDanMu(str: String?) {
        if (TMSharedPUtil.getTMToken(this).equals("")||TMSharedPUtil.getTMToken(this)==null){
            GoLoginDialog(this).show()
        }else{
            gsyPlayer.addDanmaku(str,true)
            if (TMSharedPUtil.getTMToken(this@LiveAty)!=null)
                OkGo.get<String>(Contents.BaseUrl+Contents.SEND_DANMU)
                        .params("token",TMSharedPUtil.getTMToken(this))
                        .params("live_id",intent.getIntExtra("id",0).toString())
                        .params("vote_content",str)
                        .execute(object :StringCallback(){
                            override fun onSuccess(response: Response<String>?) {
                                val str = response?.body()
                                val bean = Gson().fromJson(str, BaseBean::class.java)
                                if (bean?.code==1){

                                }
                            }
                        })
            hideBottomUIMenu()
        }

    }

    override fun onEditClick() {
        val liveInfoFgm = infoFgm as LiveInfoFgm
        liveInfoFgm.onEditClick()
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected fun hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            val v = this.window.decorView
            v.systemUiVisibility = View.GONE
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            val decorView = window.decorView
            val uiOptions = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN)
            decorView.systemUiVisibility = uiOptions
        }
    }
}
